<?php

namespace App\Services;

use App\Models\User;
use App\Models\UserAchievement;
use App\Models\UserNotification;
use Illuminate\Support\Facades\Log;

class AchievementService
{
    private $achievements = [
        'social_newbie' => [
            'key' => 'social_newbie',
            'name' => '社交新人',
            'description' => '完成首次训练',
            'category' => 'training',
            'difficulty' => 'easy',
            'condition' => 'first_training_completed',
            'rewards' => ['badge', 'basic_phrases'],
            'trigger_referral' => false,
            'points' => 10,
        ],
        'ice_breaker' => [
            'key' => 'ice_breaker',
            'name' => '冷场终结者',
            'description' => '成功挽回5次冷场情况，每次响应时间不超过10秒',
            'category' => 'skill',
            'difficulty' => 'hard',
            'condition' => 'ice_breaking_master',
            'rewards' => ['title', 'emoji_pack'],
            'trigger_referral' => true,
            'points' => 50,
        ],
        'seven_day_warrior' => [
            'key' => 'seven_day_warrior',
            'name' => '七日战士',
            'description' => '连续7天进行训练',
            'category' => 'consistency',
            'difficulty' => 'medium',
            'condition' => 'consecutive_training_7_days',
            'rewards' => ['golden_badge', 'achievement_points'],
            'trigger_referral' => true,
            'points' => 30,
        ],
        'empathy_master' => [
            'key' => 'empathy_master',
            'name' => '共情大师',
            'description' => '在安抚类场景中连续3次获得85分以上',
            'category' => 'skill',
            'difficulty' => 'hard',
            'condition' => 'empathy_expert',
            'rewards' => ['special_badge', 'empathy_guide'],
            'trigger_referral' => false,
            'points' => 40,
        ],
        'conversation_catalyst' => [
            'key' => 'conversation_catalyst',
            'name' => '对话催化剂',
            'description' => '成功完成20次训练会话',
            'category' => 'training',
            'difficulty' => 'medium',
            'condition' => 'training_sessions_20',
            'rewards' => ['badge', 'conversation_tips'],
            'trigger_referral' => false,
            'points' => 25,
        ],
        'perfect_score' => [
            'key' => 'perfect_score',
            'name' => '完美表现',
            'description' => '在任意训练中获得95分以上的最终情感分数',
            'category' => 'excellence',
            'difficulty' => 'expert',
            'condition' => 'perfect_training_score',
            'rewards' => ['platinum_badge', 'master_guide'],
            'trigger_referral' => true,
            'points' => 100,
        ],
        'social_butterfly' => [
            'key' => 'social_butterfly',
            'name' => '社交蝴蝶',
            'description' => '与所有5种不同性格的AI角色都成功对话',
            'category' => 'exploration',
            'difficulty' => 'medium',
            'condition' => 'all_characters_success',
            'rewards' => ['rainbow_badge', 'character_insights'],
            'trigger_referral' => false,
            'points' => 35,
        ],
        'helping_hand' => [
            'key' => 'helping_hand',
            'name' => '助人为乐',
            'description' => '在求助站帮助其他用户解答5个问题',
            'category' => 'community',
            'difficulty' => 'medium',
            'condition' => 'help_answers_5',
            'rewards' => ['helper_badge', 'community_points'],
            'trigger_referral' => false,
            'points' => 20,
        ],
    ];

    /**
     * 获取所有成就
     */
    public function getAllAchievements()
    {
        return array_values($this->achievements);
    }

    /**
     * 检查所有成就
     */
    public function checkAllAchievements($user)
    {
        $unlockedAchievements = [];

        foreach ($this->achievements as $key => $achievement) {
            if ($this->hasAchievement($user, $key)) {
                continue; // 已经获得的成就跳过
            }

            if ($this->checkCondition($user, $achievement['condition'])) {
                $unlockedAchievement = $this->unlockAchievement($user, $key, $achievement);
                $unlockedAchievements[] = $unlockedAchievement;
            }
        }

        return $unlockedAchievements;
    }

    /**
     * 检查特定动作触发的成就
     */
    public function checkAchievements($user, $action, array $data = [])
    {
        $unlockedAchievements = [];

        foreach ($this->achievements as $key => $achievement) {
            if ($this->hasAchievement($user, $key)) {
                continue;
            }

            if ($this->checkConditionWithAction($user, $achievement['condition'], $action, $data)) {
                $unlockedAchievement = $this->unlockAchievement($user, $key, $achievement);
                $unlockedAchievements[] = $unlockedAchievement;
            }
        }

        return $unlockedAchievements;
    }

    /**
     * 获取成就进度
     */
    public function getAchievementProgress($user, $achievementKey)
    {
        if (!isset($this->achievements[$achievementKey])) {
            return 0;
        }

        $achievement = $this->achievements[$achievementKey];
        return $this->calculateProgress($user, $achievement['condition']);
    }

    /**
     * 检查用户是否已有成就
     */
    private function hasAchievement($user, $achievementKey)
    {
        return $user->achievements()->where('achievement_key', $achievementKey)->exists();
    }

    /**
     * 检查成就条件
     */
    private function checkCondition($user, $condition)
    {
        switch ($condition) {
            case 'first_training_completed':
                return $user->statistics && $user->statistics->total_training_sessions >= 1;

            case 'ice_breaking_master':
                return $this->getIceBreakingSuccessCount($user) >= 5;

            case 'consecutive_training_7_days':
                return $user->statistics && $user->statistics->consecutive_days >= 7;

            case 'empathy_expert':
                return $this->getHighEmpathyScoreCount($user) >= 3;

            case 'training_sessions_20':
                return $user->statistics && $user->statistics->total_training_sessions >= 20;

            case 'perfect_training_score':
                return $this->hasPerfectScore($user);

            case 'all_characters_success':
                return $this->hasSuccessWithAllCharacters($user);

            case 'help_answers_5':
                return $this->getHelpAnswersCount($user) >= 5;

            default:
                return false;
        }
    }

    /**
     * 检查带动作的成就条件
     */
    private function checkConditionWithAction($user, $condition, $action, array $data)
    {
        switch ($condition) {
            case 'first_training_completed':
                return $action === 'training_completed' && $user->statistics->total_training_sessions === 1;

            case 'consecutive_training_7_days':
                return $action === 'training_completed' && $user->statistics->consecutive_days >= 7;

            case 'perfect_training_score':
                return $action === 'training_completed' && 
                       isset($data['final_emotion_score']) && 
                       $data['final_emotion_score'] >= 95;

            default:
                return $this->checkCondition($user, $condition);
        }
    }

    /**
     * 计算成就进度
     */
    private function calculateProgress($user, $condition)
    {
        switch ($condition) {
            case 'first_training_completed':
                return $user->statistics && $user->statistics->total_training_sessions > 0 ? 100 : 0;

            case 'ice_breaking_master':
                return min(100, ($this->getIceBreakingSuccessCount($user) / 5) * 100);

            case 'consecutive_training_7_days':
                return $user->statistics ? min(100, ($user->statistics->consecutive_days / 7) * 100) : 0;

            case 'training_sessions_20':
                return $user->statistics ? min(100, ($user->statistics->total_training_sessions / 20) * 100) : 0;

            case 'help_answers_5':
                return min(100, ($this->getHelpAnswersCount($user) / 5) * 100);

            default:
                return 0;
        }
    }

    /**
     * 解锁成就
     */
    private function unlockAchievement($user, $key, array $achievement)
    {
        try {
            $userAchievement = UserAchievement::create([
                'user_id' => $user->id,
                'achievement_key' => $key,
                'achievement_name' => $achievement['name'],
                'description' => $achievement['description']
            ]);

            // 发放奖励
            $this->grantRewards($user, $achievement['rewards'], $achievement['points']);

            // 发送通知
            $this->sendAchievementNotification($user, $userAchievement);

            // 触发引流
            if ($achievement['trigger_referral']) {
                $this->triggerReferral($user, $userAchievement);
            }

            Log::info('Achievement unlocked', [
                'user_id' => $user->id,
                'achievement_key' => $key,
                'achievement_name' => $achievement['name']
            ]);

            return [
                'key' => $key,
                'name' => $achievement['name'],
                'description' => $achievement['description'],
                'rewards' => $achievement['rewards'],
                'points' => $achievement['points'],
                'unlocked_at' => $userAchievement->unlocked_at,
            ];

        } catch (\Exception $e) {
            Log::error('Failed to unlock achievement', [
                'user_id' => $user->id,
                'achievement_key' => $key,
                'error' => $e->getMessage()
            ]);

            throw $e;
        }
    }

    /**
     * 发放奖励
     */
    private function grantRewards($user, array $rewards, $points)
    {
        // 增加经验值
        if ($user->statistics) {
            $user->statistics->addExperiencePoints($points);
        }

        // 这里可以实现具体的奖励发放逻辑
        // 比如解锁话术库、表情包等
        Log::info('Rewards granted', [
            'user_id' => $user->id,
            'rewards' => $rewards,
            'points' => $points
        ]);
    }

    /**
     * 发送成就通知
     */
    private function sendAchievementNotification($user, $userAchievement)
    {
        UserNotification::create([
            'user_id' => $user->id,
            'notification_type' => 'achievement',
            'title' => '🎉 恭喜解锁新成就！',
            'content' => "你获得了「{$userAchievement->achievement_name}」成就！{$userAchievement->description}",
            'scheduled_at' => now()
        ]);
    }

    /**
     * 触发引流
     */
    private function triggerReferral($user, $userAchievement)
    {
        UserNotification::create([
            'user_id' => $user->id,
            'notification_type' => 'referral',
            'title' => '🚀 技能提升显著！',
            'content' => "恭喜获得「{$userAchievement->achievement_name}」！你的社交技能已经有了很大提升，是时候在真实世界中展现你的魅力了！",
            'scheduled_at' => now()
        ]);
    }

    // 辅助方法
    private function getIceBreakingSuccessCount($user)
    {
        // 这里应该查询用户在冷场救场场景中的成功次数
        // 暂时返回模拟数据
        return $user->trainingSessions()
                   ->where('success_achieved', true)
                   ->whereHas('scenario', function ($query) {
                       $query->where('name', 'like', '%冷场%');
                   })
                   ->count();
    }

    private function getHighEmpathyScoreCount($user)
    {
        return $user->trainingSessions()
                   ->where('success_achieved', true)
                   ->where('final_emotion_score', '>=', 85)
                   ->whereHas('scenario', function ($query) {
                       $query->where('name', 'like', '%安抚%');
                   })
                   ->count();
    }

    private function hasPerfectScore($user)
    {
        return $user->trainingSessions()
                   ->where('final_emotion_score', '>=', 95)
                   ->exists();
    }

    private function hasSuccessWithAllCharacters($user)
    {
        $totalCharacters = 5; // 假设有5个角色
        $successfulCharacters = $user->trainingSessions()
                                   ->where('success_achieved', true)
                                   ->distinct('character_id')
                                   ->count('character_id');
        
        return $successfulCharacters >= $totalCharacters;
    }

    private function getHelpAnswersCount($user)
    {
        // 这里应该查询用户在求助站的回答数量
        // 暂时返回0，等实现求助功能后再完善
        return 0;
    }
}